package com.strong.config.security.point;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.strong.utils.mvc.pojo.view.ReplyEnum;
import com.strong.utils.mvc.pojo.view.ReplyVO;
import com.strong.utils.security.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static com.strong.config.WebSecurityConfig.STR_URL_LOGIN_URL;

/**
 * JWT认证入口点
 *
 * @author Simen
 * @date 2022/02/10
 */
@Slf4j
@Component("JwtAuthenticationEntryPoint")
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        // 从request头中获取Accept
        String strAccept = request.getHeader("Accept");
        if (StrUtil.isNotBlank(strAccept)) {
            // 对Accept分组为字符串数组
            String[] strsAccept = StrUtil.splitToArray(strAccept, ",");
            // 判断Accept数组中是否存在"text/html"
            if (ArrayUtil.contains(strsAccept, "text/html")) {
                // 存在"text/html"，判断为html访问，则跳转到登录界面
                response.sendRedirect(STR_URL_LOGIN_URL);
            } else {
                // 不存在"text/html"，判断为json访问，则返回未授权的json
                SecurityUtils.returnReplyJsonResponse(response, HttpServletResponse.SC_OK,
                        new ReplyVO<>(authException.getMessage(), ReplyEnum.ERROR_SERVER_ERROR));
            }
        }
    }
}
